package cn.stylefeng.guns.modular.business.frequency.orderlogistics.controller;

import cn.hutool.http.HttpUtil;
import cn.stylefeng.guns.core.enums.ReturnCode;
import cn.stylefeng.guns.core.pojo.page.AndaPageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.modular.business.frequency.banner.config.Application;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.entity.OrderLogistics;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.model.param.ErrorMsg;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.model.param.TXMapSuggestVO;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.model.result.TransportPageVO;
import cn.stylefeng.guns.modular.business.frequency.orderlogistics.service.OrderLogisticsService;
import cn.stylefeng.guns.modular.business.frequency.transport.model.param.TransportDTO;
import cn.stylefeng.guns.modular.business.util.BusinessUtil;
import cn.stylefeng.guns.modular.util.MD5Util;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 运单物流信息 控制器
 *
 * @author: yujie
 * @date: 2023/05/09 17:16
 */
@Api(tags = "在途管理")
@RequestMapping("/api/logistics")
@RestController
public class OrderLogisticsController {

    @Resource
    OrderLogisticsService logisticsService;

    @Autowired
    private BusinessUtil businessUtil;

    @ApiOperation(value = "在途列表")
    @GetMapping
    @PreAuthorize("@el.check('logistics:list')")
    public ResponseData getLogisticsList(TransportDTO orderDTO) {
        // 排序
        if (StringUtils.isBlank(orderDTO.getColumn())) {
            orderDTO.setColumn("t.create_time");
            orderDTO.setAsc(false);
        }
        // 数据权限
        getHasTransportQueryParam(orderDTO);
        //List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        //orderDTO.setDataList(empByOrgList);
        //orderDTO.setTenantId(businessUtil.getTenantId());
        return logisticsService.getLogisticsList(orderDTO);
    }

    @ApiOperation(value = "在途待跟踪运单列表")
    @GetMapping("/wait")
    @PreAuthorize("@el.check('logistics:list')")
    public ResponseData getWaitLogisticsList(TransportDTO orderDTO) {
        List<Integer> logisticsStatus = new ArrayList<>();
        logisticsStatus.add(0);
        orderDTO.setLogisticsStatus(logisticsStatus);
        // 数据权限
        getHasTransportQueryParam(orderDTO);
        //List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        //orderDTO.setDataList(empByOrgList);
        //orderDTO.setTenantId(businessUtil.getTenantId());
        Page<TransportPageVO> list = logisticsService.getWaitLogisticsList(orderDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list,orderDTO));
    }

    private void getHasTransportQueryParam(TransportDTO orderDTO) {
        if (StringUtils.isNotBlank(orderDTO.getKey())) {
            if (orderDTO.getKey().startsWith("Y")) {
                orderDTO.setTransportNo(orderDTO.getKey());
            } else if (orderDTO.getKey().startsWith("D")) {
                orderDTO.setOrderSubNo(orderDTO.getKey());
            } else {
                orderDTO.setVin(orderDTO.getKey());
            }
        }
        //// 数据权限
        //JwtUserDTO user = (JwtUserDTO) SecurityUtil.getCurrentUser(1);
        //// 最高数据权限
        //String maxDataScope = SecurityUtil.getCurrentUserMaxDataScope();
        //if (maxDataScope.equals(DataScopeEnum.THIS_LEVEL.getValue())) {
        //    // 本部门
        //    orderDTO.getDeptIds().add(user.getUser().getDeptId());
        //    //orderDTO.setUserId(user.getUser().getId());
        //} else if (maxDataScope.equals(DataScopeEnum.SELF.getValue())) {
        //    // 自己
        //    orderDTO.setUserId(user.getUser().getId());
        //} else if (maxDataScope.equals(DataScopeEnum.CUSTOMIZE.getValue())) {
        //    // 自定义部门
        //    orderDTO.getDeptIds().add(user.getUser().getDeptId());
        //    //orderDTO.setUserId(user.getUser().getId());
        //}
        List<Long> empByOrgList = businessUtil.getEmpByOrgList();
        orderDTO.setDataList(empByOrgList);
        orderDTO.setTenantId(businessUtil.getTenantId());
    }

    @ApiOperation(value = "在途已跟踪运单列表")
    @GetMapping("/has")
    @PreAuthorize("@el.check('logistics:list')")
    public ResponseData getHasLogisticsList(TransportDTO orderDTO) {
        List<Integer> logisticsStatus = new ArrayList<>();
        logisticsStatus.add(1);
        orderDTO.setLogisticsStatus(logisticsStatus);
        // 数据权限
        getHasTransportQueryParam(orderDTO);
        Page<TransportPageVO> list = logisticsService.getWaitLogisticsList(orderDTO);
        return ResponseData.andaSuccess(new AndaPageResult<>().AndaPageResult(list,orderDTO));
    }

    //@Log("运单在途跟踪")
    //@NoRepeatSubmit
    @ApiOperation(value = "运单物流跟踪")
    @PostMapping
    public ResponseData addLogistics(@Validated @RequestBody OrderLogistics orderLogistics) {
        ErrorMsg errorMsg = new ErrorMsg();
        if (!logisticsService.checkLogisticsAdd(orderLogistics, errorMsg)) {
            return ResponseData.andaSuccess(ReturnCode.RETURN_PARAM_ERROR, null, errorMsg.getErrorMsg());
        }
        logisticsService.addLogistics(orderLogistics);
        return ResponseData.andaSuccess(ReturnCode.RETURN_SUCCESS);
    }

    @ApiOperation(value = "运单物流跟踪列表")
    @GetMapping("/{transportId}")
    public ResponseData getLogisticsList(@PathVariable Long transportId) {
        List<OrderLogistics> list = logisticsService.getLogisticsListByTransportId(transportId);
        return ResponseData.andaSuccess(ReturnCode.RETURN_SUCCESS, list);
    }

    @ApiOperation(value = "地址输入提示")
    @GetMapping("/suggestion")
    public JSONObject getSuggestion(TXMapSuggestVO txMapSuggestVO) {
        String url = "http://apis.map.qq.com/ws/district/v1/search";
        Map<String, Object> param = new HashMap<>();
        param.put("key", Application.TX_MAP_KEY);
        param.put("keyword", txMapSuggestVO.getKeyword());
        String sigStr = "/ws/district/v1/search?key=" + Application.TX_MAP_KEY + "&keyword=" + txMapSuggestVO.getKeyword() + Application.TX_MAP_SECRET;
        String sig = getSig(sigStr);
        param.put("sig", sig);
//        param.put("filter", "category=基础设施");
//        param.put("address_format", "short");
        try {
            String content = HttpUtil.get(url, param);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(content);
            JSONObject jsonObject1 = new JSONObject();

            JSONArray jsonArray  = jsonObject.getJSONArray("result");
            JSONArray jsonArray1 = new JSONArray();
            if (jsonArray != null && jsonArray.size() > 0) {
                jsonArray1 = jsonArray.getJSONArray(0);
            }
            JSONArray jsonArray2 = new JSONArray();
            if (jsonArray1 != null && jsonArray1.size() > 10) {
                for (int i = 0; i < 10; i++) {
                    jsonArray2.add(jsonArray1.get(i));
                }
                jsonObject1.put("result", jsonArray2);
            } else {
                jsonObject1.put("result", jsonArray1);
            }
            return jsonObject1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getSig(String sigStr) {
        try {
            return MD5Util.encryptMd5(sigStr);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    @ApiOperation(value = "分段确认到达")
    @PostMapping("/{levelId}/arrived")
    public ResponseData arrived(@PathVariable String levelId) {
        logisticsService.confirmArrived(levelId);
        return ResponseData.success();
    }

}
